package com.hm.health.Activity;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import androidx.appcompat.app.ActionBar;

import com.goodix.RxProgressDialog.RxProgressSubscribe;
import com.goodix.fragment.MakeSureDialog;
import com.goodix.ini.IniFileUtils;
import com.goodix.utils.ToastUtils;
import com.goodix.comsdk.testsdk.IHBDTestClient;
import com.goodix.http.ApkManager;
import com.goodix.http.HttpConstants;
import com.goodix.http.jsonparams.entity.ApkInfo;
import com.goodix.http.jsonparams.response.BaseResponseEx;
import com.hm.health.BuildConfig;
import com.hm.health.MyApplication;
import com.hm.health.R;
import com.hm.health.Utils.Constans;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;

public class AboutActivity extends BaseActivity {
    ListView mListViewAbout;
    private Context mContext;
    private SimpleAdapter mSimpleAdapter;
    private String mLastAppVersion = BuildConfig.VERSION_NAME;
    private boolean mIsUploadSuccess;

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        MyApplication.getInstance().addActivity(this);
        mContext = this;
        setContentView(R.layout.activity_show_about);
        mListViewAbout = (ListView)findViewById(R.id.recyclerView);
        initActionBar();
        initView();
    }

    private void initView() {
        String[] from = {"key", "value"};
        int[] to = {R.id.tv_key, R.id.tv_value};
        mSimpleAdapter = new SimpleAdapter(this, getData(), R.layout.layout_property_item, from, to);
        mListViewAbout.setAdapter(mSimpleAdapter);

        mListViewAbout.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                TextView textView = view.findViewById(R.id.tv_key);
                view.setEnabled(false);
                if(textView.getText().equals("Software Update")) {
                    getLatestAppVersion(view);
                }
            }
        });
    }

    private void initActionBar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeButtonEnabled(true);
        setCenterTitle(R.string.about);
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    private void getLatestAppVersion(final View view) {
        mIsUploadSuccess = true;
        ApkManager.getLatestAppVersion(Constans.APP_TYPE_GHBD_DEMO_APP)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxProgressSubscribe<>(getString(R.string.get_latest_version_of_app),
                        new Observer<BaseResponseEx<ApkInfo>>() {
                            @Override
                            public void onCompleted() {
                                view.setEnabled(true);
                            }

                            @Override
                            public void onError(Throwable e) {
                                mIsUploadSuccess = false;
                                view.setEnabled(true);
                            }

                            @Override
                            public void onNext(BaseResponseEx<ApkInfo> responseEx) {
                                if ((responseEx.getStatus() != HttpConstants.RESULT_STATUS_SUCCESS)
                                        && (HttpConstants.RESULT_STATUS_DOWNLOADING != responseEx.getStatus())) {
                                    mIsUploadSuccess = false;
                                    ToastUtils.showShortToastMessage(mContext, getString(R.string.Failed_get_lastest_version_of_app));
                                } else if (responseEx.getStatus() == HttpConstants.RESULT_STATUS_SUCCESS) {
                                    if (null != responseEx.getData()) {
                                        mLastAppVersion = responseEx.getData().getVersion();
                                    }
                                    view.setEnabled(true);
                                    if (mLastAppVersion.compareToIgnoreCase(BuildConfig.VERSION_NAME) > 0) {
                                        makesureUpdateApp();
                                    } else {
                                        MakeSureDialog.showInformation(getString(R.string.no_need_to_update),getFragmentManager());
                                    }
                                }
                            }
                        }, mContext));
    }

    /**
     * 弹框确认是否下载最新版本APP
     */
    private void makesureUpdateApp() {
        MakeSureDialog makeSureDialog = new MakeSureDialog();
        makeSureDialog.setContent(getString(R.string.make_user_update_app_version_to) + mLastAppVersion + " ?");
        makeSureDialog.setDialogClickListener(new MakeSureDialog.onDialogClickListener() {
            @Override
            public void onSureClick() {
                new ApkManager().updateApk(Constans.APK_DOWNLOAD_PATH,
                        Constans.APP_TYPE_GHBD_DEMO_APP + mLastAppVersion + ".apk",
                        Constans.APP_TYPE_GHBD_DEMO_APP, mLastAppVersion, AboutActivity.this,
                        BuildConfig.APPLICATION_ID + ".fileprovider");
            }

            @Override
            public void onCancelClick() {

            }
        });

        makeSureDialog.show(getFragmentManager(), this.getClass().getName());
    }

    private String getVersionName() {
        try {
            PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);
            return info.versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            return getResources().getString(R.string.default_version_name);
        }
    }

    private String getPhoneName() {
        String manufacturer = Build.MANUFACTURER;
        String model = Build.MODEL;
        String mPhoneName = null;
        if (model.startsWith(manufacturer)) {
            mPhoneName = model;
        } else {
            mPhoneName = manufacturer + " " + model;
        }
        return mPhoneName;
    }

    private List<Map<String, String>> getData() {
        List<Map<String, String>> listData = new ArrayList<>();

        {
            // Update Apk
            Map<String, String> data = new HashMap<>();
            data.put("key", "Software Update");
            data.put("value", getString(R.string.check_for_update));
            listData.add(data);
        }

        {
            Map<String, String> data = new HashMap<>();
            data.put("key", "Phone Name");
            data.put("value", getPhoneName());
            listData.add(data);
        }

        {
            Map<String, String> data = new HashMap<>();
            data.put("key", "App Version");

            String v = "Release";
            if (BuildConfig.DEBUG) {
                v = "Debug";
            }
            data.put("value", v + " " + getVersionName());
            listData.add(data);
        }


        IHBDTestClient ihbdTestClient = MyApplication.getHBDTestClient();
        if (null != ihbdTestClient) {
            {
                String alg = ihbdTestClient.getLibVersion();
                if (null != alg) {
                    for (String v : alg.split("\n")) {
                        if (v.isEmpty()) continue;
                        String[] cols = v.split(",");
                        if (cols.length < 2) continue;
                        Map<String, String> data = new HashMap<>();
                        data.put("key", cols[0]);
                        data.put("value", cols[1]);
                        listData.add(data);
                    }
                }
            }

            {
                Map<String, String> data = new HashMap<>();
                data.put("key", "UI Config Version");
                String hbdOptionIniPath = IniFileUtils.getHbdOptionIniPath(mContext)
                        + IniFileUtils.UI_CONFIG_NAME;
                String v = IniFileUtils.getVersionCode(hbdOptionIniPath);
                data.put("value", v);
                if (v != null && !v.isEmpty()) {
                    listData.add(data);
                }
            }
        }

        return listData;
    }
}
